<template>
  <view class="page">
    <!-- 加载中或错误状态 -->
    <view v-if="!dish._id" class="loading-container">
      <view class="loading-text">加载中...</view>
    </view>

    <!-- 菜品信息（已加载） -->
    <view v-else>
      <!-- 菜品图片 -->
      <view class="image-section">
        <image class="dish-image" :src="getImageSrc(dish.image)" mode="aspectFill" />
        <view class="back-btn" @click="goBack">
          <uni-icons type="left" color="#fff" :size="24" />
        </view>
        <view class="favorite-btn" @click="toggleFavorite">
          <uni-icons 
            :type="isFavorited ? 'heart-filled' : 'heart'" 
            :color="isFavorited ? '#ef4444' : '#fff'" 
            :size="24" 
          />
        </view>
      </view>

      <!-- 菜品信息 -->
      <view class="info-section">
        <view class="header">
          <view class="left">
            <view class="name">{{ dish.name }}</view>
            <view class="tags">
              <view class="tag spiciness" :class="getSpicinessClass(dish.spiciness)">
                {{ getSpicinessText(dish.spiciness) }}
              </view>
              <view v-if="dish.is_recommended" class="tag recommend">推荐</view>
            </view>
          </view>
        </view>

        <!-- 描述 -->
        <view v-if="dish.description" class="description">
          <view class="label">简介</view>
          <view class="content">{{ dish.description }}</view>
        </view>

        <!-- 材料信息 -->
        <view v-if="dish.ingredients" class="ingredients">
          <view v-if="dish.ingredients.main_ingredients" class="ingredient-item">
            <view class="label">主材</view>
            <view class="content">{{ dish.ingredients.main_ingredients }}</view>
          </view>
          <view v-if="dish.ingredients.auxiliary_ingredients" class="ingredient-item">
            <view class="label">辅材</view>
            <view class="content">{{ dish.ingredients.auxiliary_ingredients }}</view>
          </view>
          <view v-if="dish.ingredients.seasonings" class="ingredient-item">
            <view class="label">调味品</view>
            <view class="content">{{ dish.ingredients.seasonings }}</view>
          </view>
        </view>
      </view>

      <!-- 底部操作栏 -->
      <view class="footer">
        <button 
          v-if="getItemCount(dish._id) === 0" 
          class="btn primary" 
          @click="addToCart"
        >
          加入已点
        </button>
        <view v-else class="qty-control">
          <button class="qty-btn" @click="decrementItem">
            <uni-icons type="minus" color="#111827" :size="20" />
          </button>
          <text class="qty-text">{{ getItemCount(dish._id) }}</text>
          <button class="qty-btn" @click="incrementItem">
            <uni-icons type="plus" color="#111827" :size="20" />
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { onShow, onLoad } from '@dcloudio/uni-app'
import { getImageSrc } from '@/common/image.js'
import { getSpicinessText, getSpicinessClass } from '@/common/dish.js'
import cart from '@/common/cart.js'
import { addFavorite, removeFavorite, checkFavorite } from '@/common/favorite.js'

const dish = ref({})
const isFavorited = ref(false)
const countMap = ref({})
const dishId = ref(null)
const isLoaded = ref(false)

// 获取菜品详情
const loadDish = async (dishId) => {
  try {
    const res = await uniCloud.callFunction({
      name: 'food-dishes',
      data: {
        action: 'get-dish-detail',
        data: { dishId }  // 改为 dishId 而不是 id
      }
    })
    
    if (res.result && res.result.code === 200) {
      dish.value = res.result.data
      // 检查收藏状态
      const favoriteRes = await checkFavorite(dishId)
      isFavorited.value = favoriteRes.isFavorite
    } else {
      uni.showToast({
        title: '加载菜品失败',
        icon: 'none'
      })
      uni.navigateBack()
    }
  } catch (err) {
    uni.showToast({
      title: '加载菜品失败',
      icon: 'none'
    })
    uni.navigateBack()
  }
}

// 更新购物车计数
const refreshCounts = () => {
  const items = cart.getCart()
  const map = {}
  items.forEach(it => {
    map[it.id] = Number(it.count) || 0
  })
  countMap.value = map
}

// 获取菜品在购物车中的数量
const getItemCount = (dishId) => {
  return countMap.value[dishId] || 0
}

// 加入购物车
const addToCart = () => {
  cart.addItem(dish.value, 1)
  refreshCounts()
  cart.syncTabBadge(2)
  uni.showToast({
    title: '已加入已点',
    icon: 'success'
  })
}

// 增加数量
const incrementItem = () => {
  const current = getItemCount(dish.value._id)
  cart.updateCount(dish.value._id, current + 1)
  refreshCounts()
  cart.syncTabBadge(2)
}

// 减少数量
const decrementItem = () => {
  const current = getItemCount(dish.value._id)
  const next = current - 1
  if (next <= 0) {
    cart.removeItem(dish.value._id)
  } else {
    cart.updateCount(dish.value._id, next)
  }
  refreshCounts()
  cart.syncTabBadge(2)
}

// 切换收藏
const toggleFavorite = async () => {
  if (isFavorited.value) {
    // 取消收藏
    const result = await removeFavorite(dish.value._id)
    if (result.success) {
      isFavorited.value = false
      uni.showToast({ title: '已取消收藏', icon: 'success' })
    }
  } else {
    // 添加收藏
    const result = await addFavorite(dish.value)
    if (result.success) {
      isFavorited.value = true
      uni.showToast({ title: '已收藏', icon: 'success' })
    }
  }
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

onLoad((options) => {
  // 小程序环境
  if (options.id && !isLoaded.value) {
    dishId.value = options.id
    loadDish(options.id)
    isLoaded.value = true
    refreshCounts()
  }
})

onMounted(() => {
  // H5 环境 - 如果 onLoad 没有被调用，则在这里获取参数
  if (!isLoaded.value) {
    try {
      const pages = getCurrentPages?.()
      const currentPage = pages?.[pages.length - 1]
      const id = currentPage?.$route?.query?.id
      
      if (id && !isLoaded.value) {
        dishId.value = id
        loadDish(id)
        isLoaded.value = true
      }
    } catch (err) {
      // getCurrentPages 调用失败，忽略错误
    }
  }
  
  refreshCounts()
})

onShow(() => {
  refreshCounts()
  cart.syncTabBadge(2)
})
</script>

<style lang="scss" scoped>
$primary: #10b981;
$danger: #ef4444;
$text-muted: #6b7280;

.page {
  min-height: 100vh;
  background: #f8fafc;
  padding-bottom: 120rpx;  /* 为底部按钮组预留空间 */
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400rpx; /* Match image-section height */
  background: #e5e7eb;
  color: #6b7280;
  font-size: 32rpx;
}

.image-section {
  position: relative;
  width: 100%;
  height: 400rpx;
  background: #e5e7eb;
  overflow: hidden;

  .dish-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .back-btn {
    position: absolute;
    top: max(20rpx, env(safe-area-inset-top));
    left: 20rpx;
    width: 48rpx;
    height: 48rpx;
    background: rgba(0, 0, 0, 0.3);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .favorite-btn {
    position: absolute;
    top: max(20rpx, env(safe-area-inset-top));
    right: 20rpx;
    width: 48rpx;
    height: 48rpx;
    background: rgba(0, 0, 0, 0.3);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.info-section {
  background: #fff;
  padding: 24rpx;
  margin: 16rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);

  .header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 20rpx;

    .left {
      flex: 1;

      .name {
        font-size: 36rpx;
        font-weight: 700;
        color: #0f172a;
        margin-bottom: 12rpx;
        line-height: 1.2;
      }

      .tags {
        display: flex;
        gap: 8rpx;
        flex-wrap: wrap;

        .tag {
          padding: 6rpx 12rpx;
          border-radius: 8rpx;
          font-size: 24rpx;
          font-weight: 600;

          &.spiciness {
            background: #fef3c7;
            color: #92400e;

            &.mild {
              background: #dbeafe;
              color: #0284c7;
            }

            &.light {
              background: #fef3c7;
              color: #92400e;
            }

            &.medium {
              background: #fed7aa;
              color: #92400e;
            }

            &.hot {
              background: #fca5a5;
              color: #7f1d1d;
            }
          }

          &.recommend {
            background: #dbeafe;
            color: #0284c7;
          }
        }
      }
    }
  }

  .description,
  .ingredient-item {
    margin-bottom: 24rpx;

    .label {
      font-size: 24rpx;
      font-weight: 600;
      color: #374151;
      margin-bottom: 8rpx;
    }

    .content {
      font-size: 26rpx;
      color: #6b7280;
      line-height: 1.6;
    }
  }

  .ingredients {
    padding-top: 16rpx;
    border-top: 1rpx solid #e5e7eb;

    .ingredient-item:last-child {
      margin-bottom: 0;
    }
  }
}

.footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;  /* 菜品详情页没有 TabBar，底部对齐屏幕底部 */
  background: #fff;
  padding: 16rpx 24rpx;
  padding-bottom: max(16rpx, env(safe-area-inset-bottom));
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.06);
  z-index: 10;

  .btn {
    width: 100%;
    border: none;
    border-radius: 12rpx;
    padding: 20rpx;
    font-size: 28rpx;
    font-weight: 600;
    color: #fff;

    &.primary {
      background: $primary;
    }
  }

  .qty-control {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 12rpx;
    background: #f3f4f6;
    border-radius: 12rpx;
    padding: 12rpx;

    .qty-btn {
      width: 56rpx;
      height: 56rpx;
      background: #fff;
      border: 1rpx solid #e5e7eb;
      border-radius: 8rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .qty-text {
      min-width: 60rpx;
      text-align: center;
      font-size: 28rpx;
      font-weight: 600;
      color: #111827;
    }
  }
}
</style>
